package com.clusterswisdom.horn.api.util;

import java.lang.reflect.Method;
import java.text.ParseException;

import org.apache.commons.lang3.time.DateUtils;

import com.clusterswisdom.horn.api.ioc.HornPropertyParser;
import com.clusterswisdom.horn.api.ioc.api.HornConfig;
import com.clusterswisdom.horn.api.ioc.api.ParamType;
import com.clusterswisdom.horn.api.ioc.api.ResponseField;

public class ResponseUtil {
	
	public static Object getObjectProperty(String channel, Object obj, String property) {
		if (property == null) {
			return null;
		}
		
		String[] properties = property.split("[.]");
		for (String itemProperty : properties) {
			Object value = getObjectProeprtyValue(channel, obj, itemProperty);
			obj = value;
		}
		
		return obj;
	}
	
	public static Object getObjectProeprtyValue(String channel, Object obj, String property) {
		Method method = getPropetyMethod(channel, "get", obj, property);
		if (method == null) {
			return null;
		}
		
		try {
			return method.invoke(obj);
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
			
		}
	}
	
	public static Method getPropetyMethod(String channel, String tag, Object obj, String property) {
		String getMethodName = getPropertyMethodName(channel, tag, property);
		try {
			return obj.getClass().getMethod(getMethodName);
		} catch (Exception e) {
			e.printStackTrace();
			return getPropetyMethod(channel, "is", obj, property);
			
		}
	}
	
	private static String getPropertyMethodName(String channel, String tag, String property) {
		HornPropertyParser parser = HornConfig.getConfig().getPropertyParser(channel);
		return tag + parser.getParamMethodName(property);
	}
	
	public static Object formateValue(Object value, ResponseField field) {
		if (value == null && field.getDefaultValue() != null) {
			value = field.getDefaultValue();
		}
		
		if (value == null) {
			return value;
		}
		
		if (field.getType() == ParamType.STRING) {
			return value.toString();
			
		} else if (field.getType() == ParamType.NUMBER) {
			return Long.parseLong(value.toString());
			
		} else if (field.getType() == ParamType.BOOLEAN) {
			return Boolean.parseBoolean(value.toString());
			
		} else if (field.getType() == ParamType.DATE && value instanceof String) {
			try {
				return DateUtils.parseDate(value.toString(), "yyyy-MM-dd HH:ss:mm");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}
		
		return value;
	}
}
